package cn.ieayinfo.train.mybooks.Config;
import cn.ieayinfo.train.mybooks.Entity.Permission;
import cn.ieayinfo.train.mybooks.Entity.Role;
import cn.ieayinfo.train.mybooks.Entity.User;
import cn.ieayinfo.train.mybooks.Service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User)principalCollection.getPrimaryPrincipal();
        for(Role role : user.getRoleList()) {
            authorizationInfo.addRole(role.getCode());
            for(Permission permission : role.getPermissions()) {
                authorizationInfo.addStringPermission(permission.getCode());
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        System.out.println("权限认证-->MyShiroRealm.doGetAuthenticationInfo()");
        String username = (String)token.getPrincipal();
        User user = userService.findByUsername(username);
        if(user == null) return null;
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,
                user.getPassword(),
                //ByteSource.Util.bytes(user.getPasswordSalt()),
                getName()
        );
        return authenticationInfo;
    }
}
